// In App.js in a new project

import {View, Text, StyleSheet} from 'react-native';
import {
  NavigationContainer,
  useNavigation,
  useRoute,
} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import type {NativeStackNavigationProp} from '@react-navigation/native-stack';
import type {RouteProp} from '@react-navigation/native';

interface NewType {
  itemId: number;
  otherParam: string;
}

interface CartType {
  num: number;
}

// 定义导航类型
type RootStackParamList = {
  Home: undefined;
  // 定义参参数类型
  Details: NewType;
  Cart: CartType;
};
type HomeScreenNavigationProp = NativeStackNavigationProp<RootStackParamList>;

type DetailsScreenRouteProp = RouteProp<RootStackParamList, 'Details'>;
type CartScreenRouteProp = RouteProp<RootStackParamList, 'Cart'>;

function HomeScreen() {
  const navigation = useNavigation<HomeScreenNavigationProp>();
  return (
    <View style={styles.container}>
      {/* 跳转 */}
      {/* <Text onPress={() => navigation.navigate('Home')}>Home Scre1en</Text> */}
      <Text
        onPress={() =>
          navigation.navigate(
            'Details',
            // 1 传递参数
            {
              itemId: 86,
              otherParam: 'anything you want here',
            },
          )
        }>
        Details navigate
      </Text>
      <Text onPress={() => navigation.navigate('Cart', {num: 100})}>
        购物车
      </Text>
    </View>
  );
}

function DetailsScreen() {
  const navigation = useNavigation<HomeScreenNavigationProp>();
  // 2 接收参数
  const route = useRoute<DetailsScreenRouteProp>();
  const {itemId, otherParam} = route.params;

  return (
    <View style={styles.container}>
      {/* 返回 */}
      <Text onPress={() => navigation.goBack()}>HomeDetailsScreen Scre1en</Text>
      <Text>itemId: {itemId}</Text>
      <Text>otherParam: {otherParam}</Text>
    </View>
  );
}

// 购物车页面
function CartScreen() {
  const route = useRoute<CartScreenRouteProp>();
  const {num} = route.params;
  return (
    <View>
      <Text>Cart Screen {num.toString()} </Text>
    </View>
  );
}

// 2. 创建堆栈导航器
const Stack = createNativeStackNavigator();

// 3. 配置路由结构
function RootStack() {
  return (
    <Stack.Navigator initialRouteName="Home">
      {/* 注册路由 - 首页 */}
      <Stack.Screen name="Home" component={HomeScreen} />
      {/* 注册路由 - 详情页 */}
      <Stack.Screen name="Details" component={DetailsScreen} />
      {/* 注册路由 - 购物车 */}
      <Stack.Screen name="Cart" component={CartScreen} />
    </Stack.Navigator>
  );
}

// 4. 应用入口组件
export default function App() {
  return (
    // 包裹在NavigationContainer中以启用导航功能
    <NavigationContainer>
      <RootStack />
    </NavigationContainer>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
